package com.sf.tools.common;

import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

public class VersionDao {

	public void save(Version v){
		Connection conn = ConnectionFactory.getIntance().getConnection();
		PreparedStatement pstm = null;
		String sql = "insert into tb_version(id,version,file) values(?,?,?)";
		try {
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, UUID.randomUUID().toString());
			pstm.setString(2, v.getVersion());
			pstm.setBlob(3, v.getBlob());
			pstm.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			ConnectionFactory.getIntance().close(pstm, conn);
		}
	}
	
	public Version load(){
		Connection conn = ConnectionFactory.getIntance().getConnection();
		PreparedStatement pstm = null;
		ResultSet rs = null;
		String sql = "select id,version,blob from tb_version where version=(select max(version) from tb_version)";
		try {
			pstm = conn.prepareStatement(sql);
			rs = pstm.executeQuery();
			if(rs.next()){
				String id = rs.getString(1);
				String version = rs.getString(2);
				Blob blob = rs.getBlob(3);
				return new Version(id,version,blob);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			ConnectionFactory.getIntance().close(rs, pstm, conn);
		}
		return null;
	}
}
